//
//  SCCertificateUploadVc.m
//  Shuaiche
//
//  Created by xiangtao on 2024/3/22.
//  Copyright © 2024 ShuaiChe. All rights reserved.
//

#import "SCCertificateUploadVc.h"
#import "SCCertificateUploadStyleCell.h"
#import "SCCertificateUploadSecStyleCell.h"
#import "SCCertificateIdCardUploadStyleCell.h"

@interface SCCertificateUploadVc ()<UITableViewDelegate, UITableViewDataSource, SCCertificateUploadStyleCellDelegate, SCCertificateIdCardUploadStyleCellDelegate>
{
    SCCertificateUploadStyleCell       *carDriveLicenseCell;
    SCCertificateUploadSecStyleCell    *carCertificateCell;
    SCCertificateIdCardUploadStyleCell *idCardCell;
    SCCertificateUploadSecStyleCell    *otherCertificateCell;
    NSArray    *cells;
}
@property ( strong, nonatomic) SCCarAddImageItemModel *currentItemModel;
@property ( strong, nonatomic) SCCarAddImageItemModel *frontDriveLicenseModel;
@property ( strong, nonatomic) SCCarAddImageItemModel *backDriveLicenseModel;
@property ( strong, nonatomic) SCCarAddImageItemModel *frontIdCardModel;
@property ( strong, nonatomic) SCCarAddImageItemModel *backIdCardModel;

@end

@implementation SCCertificateUploadVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 0;
    
    [self prepareData];
    
    [self initView];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 30, kSCScreenWidth, self.frame.size.height-30);
}

- (void)prepareData
{
    _frontDriveLicenseModel = [[SCCarAddImageItemModel alloc] init];
    _frontDriveLicenseModel.isAddButton = YES;
    _frontDriveLicenseModel.title = @"CERT_PIC";
    _frontDriveLicenseModel.carDescription = @"CAR_LICENSE_FRONT";
    
    _backDriveLicenseModel = [[SCCarAddImageItemModel alloc] init];
    _backDriveLicenseModel.isAddButton = YES;
    _backDriveLicenseModel.title = @"CERT_PIC";
    _backDriveLicenseModel.carDescription = @"CAR_LICENSE_BACK";
    
    _frontIdCardModel = [[SCCarAddImageItemModel alloc] init];
    _frontIdCardModel.isAddButton = YES;
    _frontIdCardModel.title = @"CERT_PIC";
    _frontIdCardModel.carDescription = @"ID_FRONT";
    
    _backIdCardModel = [[SCCarAddImageItemModel alloc] init];
    _backIdCardModel.isAddButton = YES;
    _backIdCardModel.title = @"CERT_PIC";
    _backIdCardModel.carDescription = @"ID_BACK";
    
    for (NSDictionary *dic in self.preShows) {
        NSString *title = [dic objectForKey:@"title" defaultValue:nil];
        NSString *description = [dic objectForKey:@"description" defaultValue:nil];
        if ([title isEqualToString:@"CERT_PIC"]) {
            if ([description isEqualToString:@"CAR_LICENSE_FRONT"]) {
                _frontDriveLicenseModel.isAddButton = !dic[kPicUrl];
                [_frontDriveLicenseModel addSelecteImage:nil withPath:dic[kPicUrl]];
            } else if ([description isEqualToString:@"CAR_LICENSE_BACK"]) {
                _backDriveLicenseModel.isAddButton = !dic[kPicUrl];
                [_backDriveLicenseModel addSelecteImage:nil withPath:dic[kPicUrl]];
            } else if ([description isEqualToString:@"ID_FRONT"]) {
                _frontIdCardModel.isAddButton = !dic[kPicUrl];
                [_frontIdCardModel addSelecteImage:nil withPath:dic[kPicUrl]];
            } else if ([description isEqualToString:@"ID_BACK"]) {
                _backIdCardModel.isAddButton = !dic[kPicUrl];
                [_backIdCardModel addSelecteImage:nil withPath:dic[kPicUrl]];
            }
        }
    }
}

- (void)initView {
    UIView *noticeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCScreenWidth, 30)];
    noticeView.backgroundColor = SC_HEX(0xFEFCEB);
    [self.view addSubview:noticeView];
    
    UIImageView *noticeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 7.5, 15, 15)];
    noticeIcon.image = [UIImage imageNamed:@"icon_time_tip"];
    [noticeView addSubview:noticeIcon];
    
    UILabel *noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(38, 0, kSCScreenWidth-48, 30)];
    noticeLabel.text = @"证件资料仅对公司内部人员展示";
    noticeLabel.textColor = SC_HEX(0xF96A0E);
    noticeLabel.font = SC_FONT(12);
    [noticeView addSubview:noticeLabel];
    
    UINib *uploadStyleNib = [UINib nibWithNibName:NSStringFromClass([SCCertificateUploadStyleCell class]) bundle:nil];
    UINib *uploadIdCardStyeNib = [UINib nibWithNibName:NSStringFromClass([SCCertificateIdCardUploadStyleCell class]) bundle:nil];
    
    carDriveLicenseCell = [uploadStyleNib instantiateWithOwner:nil options:nil][0];
    carDriveLicenseCell.delegate = self;
    carDriveLicenseCell.frontModel = _frontDriveLicenseModel;
    carDriveLicenseCell.backModel = _backDriveLicenseModel;
    
    carCertificateCell = [[SCCertificateUploadSecStyleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"photosCell" viewController:self preShows:self.preShows type:ImageUploadCertificateTypeCarCertificate maxPics:10];
    WEAKSELF
    carCertificateCell.reloadHeight = ^(void) {
        [weakSelf.tableView reloadData];
    };
    
    idCardCell = [uploadIdCardStyeNib instantiateWithOwner:nil options:nil][0];
    idCardCell.delegate = self;
    idCardCell.frontModel = _frontIdCardModel;
    idCardCell.backModel = _backIdCardModel;
    
    otherCertificateCell = [[SCCertificateUploadSecStyleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"photosCell" viewController:self preShows:self.preShows type:ImageUploadCertificateTypeOther maxPics:30];
    otherCertificateCell.reloadHeight = ^(void) {
        [weakSelf.tableView reloadData];
    };
    
    cells = @[
        @{@"cell": carDriveLicenseCell, @"headTitle": @"车辆行驶证照片"},
        @{@"cell": carCertificateCell, @"headTitle": @"车辆登记证照片"},
        @{@"cell": idCardCell, @"headTitle": @"身份证照片"},
        @{@"cell": otherCertificateCell, @"headTitle": @"其他证件照片"}
    ];
    
    [self.tableView reloadData];
}

- (NSMutableArray *)imagesArray {
    NSMutableArray *totalImagesArray = [NSMutableArray arrayWithCapacity:0];
    [totalImagesArray addObject:self.frontDriveLicenseModel];
    [totalImagesArray addObject:self.backDriveLicenseModel];
    [totalImagesArray addObjectsFromArray:carCertificateCell.currentModel.imagesArray];
    [totalImagesArray addObject:self.frontIdCardModel];
    [totalImagesArray addObject:self.backIdCardModel];
    [totalImagesArray addObjectsFromArray:otherCertificateCell.currentModel.imagesArray];
    
    return totalImagesArray;
}

- (UITableViewStyle)tableViewStyle {
    return UITableViewStyleGrouped;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cells[indexPath.section][@"cell"] == carCertificateCell) {
        return [carCertificateCell resizeHieight];
    }
    if (cells[indexPath.section][@"cell"] == otherCertificateCell) {
        return [otherCertificateCell resizeHieight];
    }
    return [(UITableViewCell *)cells[indexPath.section][@"cell"] frame].size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCScreenWidth, 0.1)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 32;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionHeadView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"topSectionHeadView"];
    if (!sectionHeadView) {
        sectionHeadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCScreenWidth, 10)];
        sectionHeadView.backgroundColor = SC_HEX(0xffffff);
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 14, 200, 18)];
        titleLabel.tag = 88;
        titleLabel.textColor = SC_HEX(0x222222);
        titleLabel.font = SC_FONT(14);
        [sectionHeadView addSubview:titleLabel];
    }
    UILabel *headLabel = (UILabel *)[sectionHeadView viewWithTag:88];
    headLabel.text = cells[section][@"headTitle"];
    return sectionHeadView;
}

#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cells[indexPath.section][@"cell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return cells.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark - SCCertificateUploadStyleCellDelegate
- (void)SCCertificateUploadStyleCellDidAddFrontDriveLicense
{
    self.currentItemModel = _frontDriveLicenseModel;
    [self showActionSheet];
}

- (void)SCCertificateUploadStyleCellDidDeleteFrontDriveLicense
{
    _frontDriveLicenseModel.isAddButton = YES;
    _frontDriveLicenseModel.title = nil;
    _frontDriveLicenseModel.carDescription = nil;
    _frontDriveLicenseModel.asset = nil;
    [_frontDriveLicenseModel addSelecteImage:nil withPath:nil];
    self.currentItemModel = _frontDriveLicenseModel;
    carDriveLicenseCell.frontModel = self.currentItemModel;
}

- (void)SCCertificateUploadStyleCellDidAddBackDriveLicense
{
    self.currentItemModel = _backDriveLicenseModel;
    [self showActionSheet];
}

- (void)SCCertificateUploadStyleCellDidDeleteBackDriveLicense
{
    _backDriveLicenseModel.isAddButton = YES;
    _backDriveLicenseModel.title = nil;
    _backDriveLicenseModel.carDescription = nil;
    _backDriveLicenseModel.asset = nil;
    [_backDriveLicenseModel addSelecteImage:nil withPath:nil];
    self.currentItemModel = _backDriveLicenseModel;
    carDriveLicenseCell.backModel = self.currentItemModel;
}

#pragma mark - SCCertificateIdCardUploadStyleCellDelegate
- (void)SCCertificateIdCardUploadStyleCellDidAddFrontIdCard
{
    self.currentItemModel = _frontIdCardModel;
    [self showActionSheet];
}

- (void)SCCertificateIdCardUploadStyleCellDidDeleteFrontIdCard
{
    _frontIdCardModel.isAddButton = YES;
    _frontIdCardModel.title = nil;
    _frontIdCardModel.carDescription = nil;
    _frontIdCardModel.asset = nil;
    [_frontIdCardModel addSelecteImage:nil withPath:nil];
    self.currentItemModel = _frontIdCardModel;
    idCardCell.frontModel = self.currentItemModel;
}

- (void)SCCertificateIdCardUploadStyleCellDidAddBackIdCard
{
    self.currentItemModel = _backIdCardModel;
    [self showActionSheet];
}

- (void)SCCertificateIdCardUploadStyleCellDidDeleteBackIdCard
{
    _backIdCardModel.isAddButton = YES;
    _backIdCardModel.title = nil;
    _backIdCardModel.carDescription = nil;
    _backIdCardModel.isAddButton = YES;
    _backIdCardModel.asset = nil;
    [_backIdCardModel addSelecteImage:nil withPath:nil];
    self.currentItemModel = _backIdCardModel;
    idCardCell.backModel = self.currentItemModel;
}

- (void)showActionSheet {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showPhotoAlume];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showCamera {
    [self dismissViewControllerAnimated:NO completion:nil];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        // picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)showPhotoAlume {
    
    TZImagePickerController *imagePickController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
//    imagePickController.minImagesCount = 1;
    //是否 在相册中显示拍照按钮
    imagePickController.allowTakePicture = NO;
    //是否可以选择显示原图
    imagePickController.allowPickingOriginalPhoto = YES;
    //是否 在相册中可以选择视频
    imagePickController.allowPickingVideo = NO;
//    imagePickController.showSelectBtn = YES;
    imagePickController.naviBgColor = [UIColor whiteColor];
    imagePickController.naviTitleColor = [UIColor blackColor];
    imagePickController.barItemTextColor = [UIColor blackColor];
    imagePickController.statusBarStyle = UIStatusBarStyleDefault;
    //    imagePickController.selectedAssets = _currentModel.selectedAssets;
    imagePickController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickController.navLeftBarButtonSettingBlock = ^(UIButton *lefyButton){
        [lefyButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    };
    [self presentViewController:imagePickController animated:YES completion:nil];
}

#pragma mark -- Photo Fetch

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    self.currentItemModel.isAddButton = NO;
    self.currentItemModel.image = image;
    self.currentItemModel.fillImage = YES;
    self.currentItemModel.title = @"CERT_PIC";
    if (self.currentItemModel == _frontDriveLicenseModel) {
        self.currentItemModel.carDescription = @"CAR_LICENSE_FRONT";
        carDriveLicenseCell.frontModel = self.currentItemModel;
    } else if (self.currentItemModel == _backDriveLicenseModel) {
        self.currentItemModel.carDescription = @"CAR_LICENSE_BACK";
        carDriveLicenseCell.backModel = self.currentItemModel;
    } else if (self.currentItemModel == _frontIdCardModel) {
        self.currentItemModel.carDescription = @"ID_FRONT";
        idCardCell.frontModel = self.currentItemModel;
    } else if (self.currentItemModel == _backIdCardModel) {
        self.currentItemModel.carDescription = @"ID_BACK";
        idCardCell.backModel = self.currentItemModel;
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    self.currentItemModel.isAddButton = NO;
    self.currentItemModel.fillImage = YES;
    self.currentItemModel.title = @"CERT_PIC";
    for (NSInteger i = 0; i < photos.count; i++) {
        UIImage *image = photos[i];
        PHAsset *asset = assets[i];
        self.currentItemModel.asset = asset;
        [self.currentItemModel addSelecteImage:image withPath:nil];
    }
        
    if (self.currentItemModel == _frontDriveLicenseModel) {
        self.currentItemModel.carDescription = @"CAR_LICENSE_FRONT";
        carDriveLicenseCell.frontModel = self.currentItemModel;
    } else if (self.currentItemModel == _backDriveLicenseModel) {
        self.currentItemModel.carDescription = @"CAR_LICENSE_BACK";
        carDriveLicenseCell.backModel = self.currentItemModel;
    } else if (self.currentItemModel == _frontIdCardModel) {
        self.currentItemModel.carDescription = @"ID_FRONT";
        idCardCell.frontModel = self.currentItemModel;
    } else if (self.currentItemModel == _backIdCardModel) {
        self.currentItemModel.carDescription = @"ID_BACK";
        idCardCell.backModel = self.currentItemModel;
    }
}


@end
